<template>
  <div class="user-management-container">
    <!-- 页面标题和操作区 -->
    <div class="page-header">
      <h1>用户管理</h1>
      <el-button 
        type="primary" 
        icon="Plus" 
        @click="openAddUserDialog"
      >
        新增用户
      </el-button>
    </div>

    <!-- 加载状态 -->
    <el-loading v-if="loading" fullscreen />

    <!-- 用户表格 -->
    <el-table 
      :data="filteredUsers" 
      border 
      style="width: 100%; margin-top: 20px;"
      :header-cell-style="{ background: '#f5f7fa', fontWeight: 'bold' }"
      v-loading="tableLoading"
    >
      <el-table-column 
        prop="id" 
        label="ID" 
        width="80" 
        align="center"
      ></el-table-column>
      <el-table-column 
        prop="name" 
        label="姓名" 
        align="center"
      ></el-table-column>
      <el-table-column 
        prop="email" 
        label="邮箱" 
        align="center"
      ></el-table-column>
      <el-table-column 
        prop="role" 
        label="角色" 
        align="center"
      >
        <template #default="scope">
          <el-tag :type="scope.row.role === 'admin' ? 'primary' : 'success'">
            {{ scope.row.role === 'admin' ? '管理员' : '普通用户' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column 
        prop="status" 
        label="状态" 
        align="center"
      >
        <template #default="scope">
          <el-switch 
            v-model="scope.row.status" 
            active-color="#13ce66" 
            inactive-color="#ff4949"
            :disabled="true"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column 
        label="操作" 
        width="200" 
        align="center"
      >
        <template #default="scope">
          <el-button 
            type="primary" 
            size="small" 
            icon="Edit"
            @click="handleEdit(scope.row)"
          ></el-button>
          <el-button 
            type="danger" 
            size="small" 
            icon="Delete"
            @click="handleDelete(scope.row)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50]"
        :total="totalUsers"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑用户对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEditMode ? '编辑用户' : '新增用户'"
      :width="600"
      :close-on-click-modal="false"
    >
      <el-form
        ref="userFormRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        style="margin-top: 20px;"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="formData.name" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="formData.role" placeholder="请选择角色">
            <el-option label="管理员" value="admin"></el-option>
            <el-option label="普通用户" value="user"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="formData.status" active-text="启用" inactive-text="禁用"></el-switch>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="formData.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          ></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="isEditMode ? handleUpdate() : handleCreate()"
        >
          {{ isEditMode ? '更新' : '创建' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, getCurrentInstance } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import request from './utils/request';

// 状态管理
const users = ref([]);
const loading = ref(true);
const tableLoading = ref(false);

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const totalUsers = ref(0);

// 过滤后的用户列表（用于分页）
const filteredUsers = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value;
  return users.value.slice(startIndex, startIndex + pageSize.value);
});

// 对话框相关
const dialogVisible = ref(false);
const isEditMode = ref(false);
const currentEditId = ref(null);
const userFormRef = ref(null);

// 表单数据
const formData = reactive({
  name: '',
  email: '',
  role: 'user',
  status: true,
  remark: ''
});

// 表单验证规则
const formRules = reactive({
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
});

// 获取用户列表
const fetchUsers = async () => {
  try {
    tableLoading.value = true;
    const response = await request.get('/users', {
      params: {
        page: currentPage.value,
        pageSize: pageSize.value
      }
    });
    users.value = response.data;
    totalUsers.value = response.total;
  } catch (error) {
    console.error('获取用户列表失败:', error);
  } finally {
    tableLoading.value = false;
    loading.value = false;
  }
};

// 分页事件处理
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
  fetchUsers();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchUsers();
};

// 打开新增用户对话框
const openAddUserDialog = () => {
  // 重置表单
  userFormRef.value?.resetFields();
  formData.status = true;
  formData.role = 'user';
  
  isEditMode.value = false;
  dialogVisible.value = true;
};

// 处理编辑
const handleEdit = (row) => {
  // 填充表单数据
  formData.name = row.name;
  formData.email = row.email;
  formData.role = row.role;
  formData.status = row.status;
  formData.remark = row.remark || '';
  
  currentEditId.value = row.id;
  isEditMode.value = true;
  dialogVisible.value = true;
};

// 处理删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 ${row.name} 吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    await request.delete(`/users/${row.id}`);
    ElMessage.success('删除成功');
    fetchUsers(); // 重新获取列表
  } catch (error) {
    // 取消删除时不做处理
    if (error !== 'cancel') {
      console.error('删除失败:', error);
    }
  }
};

// 处理创建新用户
const handleCreate = async () => {
  try {
    // 表单验证
    await userFormRef.value.validate();
    
    await request.post('/users', formData);
    ElMessage.success('用户创建成功');
    dialogVisible.value = false;
    fetchUsers(); // 重新获取列表
  } catch (error) {
    if (error.name !== 'ValidationError') {
      console.error('创建用户失败:', error);
    }
  }
};

// 处理更新用户
const handleUpdate = async () => {
  try {
    // 表单验证
    await userFormRef.value.validate();
    
    await request.put(`/users/${currentEditId.value}`, formData);
    ElMessage.success('用户更新成功');
    dialogVisible.value = false;
    fetchUsers(); // 重新获取列表
  } catch (error) {
    if (error.name !== 'ValidationError') {
      console.error('更新用户失败:', error);
    }
  }
};

// 页面加载时获取用户列表
onMounted(() => {
  fetchUsers();
});
</script>

<style scoped>
.user-management-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

h1 {
  margin: 0;
  font-size: 20px;
  color: #333;
}
</style>